#include "SerialClient.h"
#include <QDebug>

using namespace FCMiddleware;

SerialClient::SerialClient(QObject *parent)
	: QObject(parent)
{
	_portName = "COM1";
	_baud = 115200;
	_parity = QSerialPort::NoParity;

	_serialPort = NULL;
}

SerialClient::SerialClient(const QString& portName, unsigned int baud, QObject *parent)
	: QObject(parent)
{
	_portName = portName;
	_baud = baud;
	_parity = QSerialPort::NoParity;

	_serialPort = NULL;
}

SerialClient::~SerialClient()
{
	if (_serialPort == NULL)
		return;

	close();
}

void SerialClient::setPortParams(const QString& portName, unsigned int baud, QSerialPort::Parity parity)
{
	_portName = portName;
	_baud = baud;
	_parity = QSerialPort::NoParity;
}

int SerialClient::open()
{
	Q_ASSERT(_serialPort == NULL);

	_serialPort = new QSerialPort();
	_serialPort->setPortName(_portName);
	_serialPort->setBaudRate(_baud);
	_serialPort->setParity(_parity);
	_serialPort->setDataBits(QSerialPort::Data8);
	_serialPort->setStopBits(QSerialPort::OneStop);
	if (!_serialPort->open(QIODevice::ReadWrite))
	{
		qDebug() << _serialPort->errorString();
		int err = _serialPort->error();

		delete _serialPort;
		_serialPort = NULL;

		return err;
	}

	_serialPort->setReadBufferSize(65536);
	return QSerialPort::NoError;
}

void SerialClient::close()
{
	Q_ASSERT(_serialPort != NULL);

	_serialPort->close();
	delete _serialPort;
	_serialPort = NULL;
}

int SerialClient::recv(unsigned char* buff, unsigned short size, int* err)
{
	Q_ASSERT(_serialPort != NULL);

	if (!_serialPort->waitForReadyRead(5))
	{
		*err = _serialPort->error();
		if (*err != QSerialPort::TimeoutError)
		{
			qDebug() << _serialPort->errorString();
			return -1;
		}
		else return 0;
	}
	qint64 ret = _serialPort->bytesAvailable();
	if (ret == 0)
		return 0;

	if (ret < size)
		size = ret;

	ret = _serialPort->read((char*)buff, size);
	if (ret == -1)
	{
		*err = _serialPort->error();
		qDebug() << _serialPort->errorString();
		return -1;
	}
	else return ret;
}

int SerialClient::send(char* buff, unsigned short size, int* err)
{
	Q_ASSERT(_serialPort != NULL);

	int ret = _serialPort->write(buff, size);
	if (ret == -1)
	{
		*err = _serialPort->error();
		qDebug() << _serialPort->errorString();

		return -1;
	}

	if (!_serialPort->waitForBytesWritten(5))
	{
		*err = _serialPort->error();
		if (*err != QSerialPort::TimeoutError)
		{
			qDebug() << _serialPort->errorString();
			return -1;
		}
		else return 0;
	}
	else return 0;
}

